# coding=utf-8
# Copyright 2025 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Definitions of exceptions used by AndroidEnv."""


class AndroidEnvError(Exception):
  """Base class for all known errors generated by AndroidEnv."""

  # An integer that identifies this class of error.
  # Subclasses should use a different value.
  ERROR_CODE: int = 0


class ReadObservationError(AndroidEnvError):
  """When the environment is unable to obtain an observation from a simulator."""

  ERROR_CODE = 1


class CoordinatorError(AndroidEnvError):
  """Error raised by the Coordinator."""

  ERROR_CODE = 2


class TooManyRestartsError(CoordinatorError):
  """The number of restarts has exceeded _MAX_RESTART_TRIES."""

  ERROR_CODE = 3


class AdbControllerError(AndroidEnvError):
  """Errors that can be raised by ADBController."""

  ERROR_CODE = 4


class SimulatorError(AndroidEnvError):
  """Errors that can be raised by a simulator."""

  ERROR_CODE = 5


class SendActionError(AndroidEnvError):
  """Raised when action couldn't be sent successfully."""

  ERROR_CODE = 6


class StepCommandError(AndroidEnvError):
  """Raised when setup step interpreter cannot process a command."""

  ERROR_CODE = 7


class WaitForAppScreenError(StepCommandError):
  """Raised when the wait_for_app_screen success check is not met."""

  ERROR_CODE = 8


class CheckInstallError(StepCommandError):
  """Raised when the check_install success check is not met."""

  ERROR_CODE = 9


def from_code(code: int, msg: str = '') -> AndroidEnvError | None:
  """Returns an AndroidEnvError instance from the given arguments."""

  code_to_error = {
      0: AndroidEnvError,
      1: ReadObservationError,
      2: CoordinatorError,
      3: TooManyRestartsError,
      4: AdbControllerError,
      5: SimulatorError,
      6: SendActionError,
      7: StepCommandError,
      8: WaitForAppScreenError,
      9: CheckInstallError,
  }

  if code in code_to_error:
    return code_to_error[code](msg)
